package com.fengye.api.runner;

import com.fengye.common.constants.CommonConstant;
import com.fengye.common.domain.entity.Article;
import com.fengye.api.mapper.ArticleMapper;
import com.fengye.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ViewCountRunner
 *
 * @author 枫叶fy
 * @description 浏览数runner，服务启动的时候，初始化redis浏览数（从数据库中获取原始数据）
 * @since 2024/4/9 22:06
 */
@Slf4j
@Component
public class ViewCountRunner implements CommandLineRunner {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void run(String... args) throws Exception {
        log.info("服务启动了，开始从数据库获取数据并初始化浏览数到redis");

        // 获取文章信息 id viewCount
        List<Article> articles = articleMapper.selectList(null);
        // 生成浏览数map
        Map<String, Object> viewCountMap = articles.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(), Article::getViewCount));

        // 存储到redis
        redisUtils.hPutAll(CommonConstant.ARTICLE_VIEW_COUNT_REDIS_KEY, viewCountMap);
    }
}
